package cn.elead.it.sso.core.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.elead.it.sso.core.constant.GlobalVariable;
import cn.elead.it.sso.core.login.SsoTokenLoginHelper;
import cn.elead.it.sso.core.model.SsoResponse;
import cn.elead.it.sso.core.model.SsoUser;
import cn.elead.it.sso.core.path.AntPathMatcher;
import cn.elead.it.sso.core.store.SsoLoginStore;
import cn.elead.it.sso.core.util.JWTUtils;
import cn.elead.it.sso.core.util.JedisUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * oauth sso filter
 * 
 * @author luopeng
 *
 */
@SuppressWarnings("serial")
public class SsoOauthFilter extends SsoFilter {

	private static Logger logger = LoggerFactory.getLogger(SsoOauthFilter.class);

	private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

	// private String ssoServer;
	private String logoutPath;
	private String codeCallback;
	//private String clientId;
	private String clientSecret;
	
	private String ssoUser;
	

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

		// ssoServer = filterConfig.getInitParameter(GlobalVariable.SSO_SERVER);
		logoutPath = filterConfig.getInitParameter(GlobalVariable.SSO_LOGOUT_PATH);
		codeCallback = filterConfig.getInitParameter(GlobalVariable.SSO_CODE_CALLBACK);
		//clientId = filterConfig.getInitParameter(GlobalVariable.SSO_CLIENTID);
		clientSecret = filterConfig.getInitParameter(GlobalVariable.SSO_CLIENTSECRET);
		ssoUser = filterConfig.getInitParameter(GlobalVariable.SSO_USER);
		addExcludedPath(filterConfig);
		logger.info("SsoOauthFilter init.");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		// make url
		String servletPath = req.getServletPath();

		// excluded path check
		for (String excludedPath : excludedPaths) {
			String uriPattern = excludedPath.trim();

			// 支持ANT表达式
			if (antPathMatcher.match(uriPattern, servletPath)) {
				// excluded path, allow
				chain.doFilter(request, response);
				return;
			}

		}

		// codeCallback filter
		if (codeCallback != null && codeCallback.trim().length() > 0 && codeCallback.equals(servletPath)) {
			// 获取code值
			String code = request.getParameter(GlobalVariable.OAUTH_CODE_RESPONSE_TYPE);
			if (StrUtil.isBlank(code)) {
				writeValueAsJson(resp, req, new SsoResponse().setStatus(401).setMsg("code不存在!"));
				return;
			}
			// code在redis是否存在
			Object value = JedisUtil.getObjectValue(code);
			if (null == value) {
				writeValueAsJson(resp, req, new SsoResponse().setStatus(401).setMsg("code已经失效!"));
				return;
			}
			// 转成SsoUser
			SsoUser ssoUser = (SsoUser) value;
			// 判断客户端秘钥是否一致
			//if (!StrUtil.equalsIgnoreCase(ssoUser.getClientSecret(), clientSecret)) {
				//writeValueAsJson(resp, req, new SsoResponse().setStatus(400).setMsg("clientSecret不正确!"));
				//return;
			//}
			
			// 1、make sso user
			ssoUser.setExpireMinite(SsoLoginStore.getRedisExpireMinite());
			ssoUser.setExpireFreshTime(System.currentTimeMillis());

			// 2、generate sessionId + storeKey
			//String sessionId = SsoSessionIdHelper.makeSessionId(ssoUser);
			// code解密为sessionId
			String sessionId = JWTUtils.parseSession(code);

			// 3、login, store storeKey
			SsoTokenLoginHelper.login(sessionId, ssoUser);
			
			// response
			writeValueAsJson(resp, req, new SsoResponse().setStatus(200).setResult(sessionId).setMsg("通过code换取token成功!"));
			return;
		}
		
		// logout filter
		if (logoutPath != null && logoutPath.trim().length() > 0 && logoutPath.equals(servletPath)) {
			// logout
			SsoTokenLoginHelper.logout(req);
			// response
			writeValueAsJson(resp, req, new SsoResponse().setStatus(200).setMsg("登出成功!"));
			return;
		}
		
		if (ssoUser != null && ssoUser.trim().length() > 0 && ssoUser.equals(servletPath)) {
			// login filter
			SsoUser ssoUser = SsoTokenLoginHelper.loginCheck(req);
			if (ObjectUtil.isNotNull(ssoUser)) {
				// response
				writeValueAsJson(resp, req, new SsoResponse().setStatus(200).setResult(ssoUser).setMsg("获取用户成功"));
				return;
			}else {
				// response
				writeValueAsJson(resp, req, new SsoResponse().setStatus(401).setMsg("获取用户失败"));
				return;
			}
		}
		

		// login filter
		SsoUser ssoUser = SsoTokenLoginHelper.loginCheck(req);
		if (ssoUser == null) {
			// response
			writeValueAsJson(resp, req, new SsoResponse().setStatus(401).setMsg("sessionId不存在或是已失效!"));
			return;
		}

		// ser sso user
		request.setAttribute(GlobalVariable.SSO_USER, ssoUser);
		request.setAttribute("API_UID", ssoUser.getUserId());

		// already login, allow
		chain.doFilter(request, response);
		return;
	}

}
